<template>
	<view class="body">
		<!-- 加载指示器 -->
		<up-loading-page :loading="isLoading" />
		<!-- 发布者信息 -->
		<view class="publisher">
			<up-avatar :src="userInfor.avatar" size="70rpx" shape="circle" class="avatar"></up-avatar>
			<view class="info">
				<up-text :text="userInfor.username" class="username"></up-text>
				<view class="meta">
					<up-tag :text="userInfor.grade" plain size="mini" type="success" plainFill
						class="grade-tag"></up-tag>
					<up-tag :text="order.views" plain size="mini" icon="eye" type="success" plainFill
						class="views-tag"></up-tag>
					<up-tag :text="order.createTime" plain size="mini" type="success" plainFill
						class="time-tag"></up-tag>
				</view>
			</view>
		</view>

		<!-- 任务标签和赏金 -->
		<view class="task-meta" v-if="!isLoading">
			<up-tag :text="order.typeId" type="warning" plain plainFill borderColor="transparent"
				class="task-tag"></up-tag>
			<up-text text="赏金：" class="bounty-label"></up-text>
			<up-text :text="order.price" class="bounty-amount"></up-text>
		</view>

		<!-- 任务要求 -->
		<view class="task-requirements" v-if="!isLoading">
			<up-text :text="order.describe" class="requirements-content"></up-text>
		</view>

		<!-- 任务状态流程 -->
		<view class="steps-wrap" v-if="!isLoading">
			<up-steps :current="order.state" direction="horizontal" activeIcon="checkmark" inactiveIcon="arrow-right"
				class="horizontal-steps">
				<up-steps-item title="查看需求"></up-steps-item>
				<up-steps-item title="接单帮忙"></up-steps-item>
				<up-steps-item title="完成订单"></up-steps-item>
				<up-steps-item title="佣金到账"></up-steps-item> <!-- 修正重复项 -->
			</up-steps>
		</view>
		<view v-if="!isLoading">
			<!-- 接单人信息区域：点击接单后显示 <run-user/> 组件 -->
			<view class="taker-info" v-if="order.state !== 0&&order.takeUserId !== userId&&
			order.userId!=userId">
				<!-- 替换为 run-user 组件 -->
				<!-- <run-user/> -->
				展示接单人信息{{order.takeUserId}}用户{{userId}}
			</view>
			<view class="taker-info" v-else-if="order.state === 0&&order.takeUserId===null">
				<!-- 接单按钮：添加点击事件 -->
				<up-button type="primary" icon="接单" text="接单" class="take-btn" @click="handleTakeOrder" <!-- 绑定点击事件 -->
					></up-button>
			</view>
			<view class="taker-info" v-else-if="order.state === 2&&order.userId=== userId">
				<up-button type="primary" icon="付款" text="付款" class="take-btn" @click="handlePayOrder" <!-- 绑定点击事件 -->
					></up-button>
			</view>
			<view class="taker-info" v-else-if="order.state === 1&&userInfor.takeUserId === userId">
				<view>
					<view>
						<up-text type="info" text="取件码"></up-text>
						<up-text :text="order.code"></up-text>
					</view>
					<view>
						<up-text type="info" text="手机尾号"></up-text>
						<up-text :text="order.phoneEnd"></up-text>
					</view>
					<view>
						<up-text type="info" text="备注"></up-text>
						<up-text :text="order.remark"></up-text>
					</view>
				</view>
				<up-button type="primary" icon="完成" text="完成" class="take-btn" @click="handleFinishOrder" <!-- 绑定点击事件
					-->
					></up-button>
			</view>
		</view>


		<!-- 底部操作 -->
		<view class="bottom" v-if="!isLoading">
			<up-tag icon="eye" :text="order.views" plain shape="circle" borderColor="transparent"
				class="views-tag"></up-tag>
			<view class="actions">
				<up-button type="primary" icon="share" plain class="share-btn"></up-button>
				<up-button type="primary" icon="like" plain class="like-btn"></up-button>
			</view>
		</view>
	</view>
</template>

<script setup lang="ts">
	import { onLoad } from "@dcloudio/uni-app";
	import { ref, watch } from "vue";
	import { acceptRun, getRunById, getShopOrder, updateState } from "../../apis/runAPI";

	const order = ref({});
	//获取用户id
	const userInfo = uni.getStorageSync('userInfo');
	console.log("yonghuxinxi11", userInfo)
	const userId = ref(userInfo?.userId || ''); // 初始化为空或从存储中获取
	console.log("userId11", userId.value)
	const userInfor = ref<any>({});
	const isLoading = ref(true); // 添加加载状态

	// 获取订单信息 - 修改为异步函数
	const getRun = async () => {
		try {
			isLoading.value = true;
			const res = await getRunById(userInfor.value.id);
			if (res.data.code === 200) {
				// ✅ 确保在这里赋值
				order.value = res.data.data;
				console.log("订单数据已加载", order.value);
			} else {
				console.error("获取订单失败:", res.data.msg);
			}
		} catch (error) {
			console.error("网络请求错误:", error);
			uni.showToast({ title: '加载失败，请重试', icon: 'error' });
		} finally {
			isLoading.value = false;
		}
	};
	const handlePayOrder = () => {
		getShopOrder(order.value.runNumber).then((res : any) => {
			console.log("dingdan",order.value)
			console.log("danhao",order.value.runNumber)
			console.log("订单信息", res.data)
			if (res.data.code === 200) {
				uni.hideLoading();
				console.log("订单信息", res.data.data)
				// 订单获取成功，跳转到支付页面并传递订单ID和订单编号
				uni.navigateTo({
					url: `/pages/shop/shop-play?orderId=${res.data.data.id}&orderNumber=${res.data.data.orderNumber}&totalAmount=${res.data.data.totalAmount}`
				});
			} else {
				uni.hideLoading();
				uni.showToast({ title: '获取订单失败', icon: 'none' });
			}

		})
	}

	// 接单事件处理
	const handleTakeOrder = async () => {
		if (!order.value.runNumber || !userId.value) {
			uni.showToast({ title: '参数错误', icon: 'none' });
			return;
		}

		try {
			const res = await acceptRun(order.value.runNumber, userId.value);
			if (res.data.code === 200) {
				uni.showToast({ title: '接单成功', icon: 'success' });
				// ✅ 重新获取最新数据
				await getRun();
			} else {
				uni.showToast({ title: res.data.msg || '接单失败', icon: 'error' });
			}
		} catch (error) {
			uni.showToast({ title: '网络错误，接单失败', icon: 'error' });
		}
	};

	// 完成订单事件
	const handleFinishOrder = async () => {
		try {
			const res = await updateState(order.value.id);
			if (res.data.code === 200) {
				uni.showToast({ title: '订单已完成', icon: 'success' });
				// ✅ 重新获取最新数据
				await getRun();
			} else {
				uni.showToast({ title: res.data.msg || '操作失败', icon: 'error' });
			}
		} catch (error) {
			uni.showToast({ title: '网络错误', icon: 'error' });
		}
	};

	onLoad(async (options) => {
		if (options.item) {
			userInfor.value = JSON.parse(decodeURIComponent(options.item));
		}
		const userInfo = uni.getStorageSync('userInfo');
		console.log("yonghuxinxi10", userInfo)
		// 正确更新响应式变量的值
		if (userInfo && userInfo.userId) {
			userId.value = userInfo.userId;
			console.log("userId13", userId)
		}
		// ✅ 使用 await 确保异步操作完成
		await getRun();

		// 此时 order.value 已有数据
		console.log("页面加载完成后的订单数据", order.value);
	});

	// 可选：添加监听器观察数据变化
	watch(order, (newVal) => {
		console.log("订单数据变化:", newVal);
	}, { deep: true });
</script>

<style lang="scss">
	/* 原有样式不变 */
	.body {
		padding: 20rpx;
		background-color: #fff;
	}

	/* 发布者信息 */
	.publisher {
		display: flex;
		align-items: center;
		margin-bottom: 20rpx;

		.avatar {
			margin-right: 20rpx;
		}

		.info {
			flex: 1;

			.username {
				font-size: 32rpx;
				font-weight: bold;
				margin-bottom: 10rpx;
			}

			.meta {
				display: flex;
				gap: 10rpx;
				font-size: 24rpx;
				color: #999;
			}
		}
	}

	/* 任务标签和赏金 */
	.task-meta {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;

		.task-tag {
			padding: 10rpx 20rpx;
			background-color: #fef3e7;
			border-radius: 20rpx;
			font-size: 28rpx;
			font-weight: bold;
			color: #ff6600;
		}

		.bounty-label {
			font-size: 28rpx;
			color: #999;
		}

		.bounty-amount {
			font-size: 28rpx;
			color: #ff4444;
			font-weight: bold;
		}
	}

	/* 任务要求 */
	.task-requirements {
		padding: 20rpx;
		background-color: #f5f5f5;
		border-radius: 20rpx;
		margin-bottom: 20rpx;

		.requirements-content {
			font-size: 28rpx;
			line-height: 1.5;
		}
	}

	/* 任务状态流程 */
	.steps-wrap {
		width: 100%;
		overflow-x: auto;
		/* 内容溢出时滚动 */
		padding: 15px;
	}

	.horizontal-steps {
		display: flex;
		flex-direction: row;
		/* 强制水平排列 */
		align-items: center;
		/* 垂直居中 */
		white-space: nowrap;
		/* 禁止换行 */
	}

	.up-steps-item {
		flex: 0 0 auto;
		/* 不收缩，保持宽度 */
		margin-right: 20px;
		/* 步骤间距 */
		text-align: center;
		/* 文字居中 */
	}


	/* 接单人信息 */
	.taker-info {
		padding: 20rpx;
		border: 2rpx solid #e6f7ff;
		border-radius: 30rpx;
		margin-bottom: 20rpx;

		.take-btn {
			width: 100%;
			height: 80rpx;
			line-height: 80rpx;
			font-size: 30rpx;
		}
	}

	/* 底部操作 */
	.bottom {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;

		.views-tag {
			font-size: 24rpx;
			color: #999;
		}

		.actions {
			display: flex;
			gap: 20rpx;
		}

		.share-btn,
		.like-btn {
			font-size: 40rpx;
			color: #999;
		}
	}
</style>